package com.thread.async;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author wangyingjie
 * @date
 * @remark 主线程等待自线程全部走完才完成，靠计数器到0来控制
 */
public class CounDownLatchDemo {
    /**
     * 线程计数器
     */
    private static CountDownLatch countDownLatch = new CountDownLatch(10);

    public static void main(String[] args) throws InterruptedException {

        //异步开启10个线程，等待10个线程全部完成，再继续执行主线程
        ExecutorService threadPool = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            threadPool.submit(() -> {
                try {
                    if (finalI == 9 ){
                        throw new Exception();
                    }
                    test(countDownLatch.getCount());
                }catch (Exception e){
                    System.out.println(e.getMessage());
                }finally {
                    //不管任务是否执行完，计数器减1
                    countDownLatch.countDown();
                }
                    });
        }
        countDownLatch.await();
//        countDownLatch.await(5, TimeUnit.SECONDS);
        System.out.println("等待完成。。计数器此时是"+countDownLatch.getCount());
        threadPool.shutdown();
    }

    /**
     * 执行任务的方法
     */
    private static void test(long count) throws InterruptedException {
        System.out.println("任务执行开始等待，此时计数器是："+countDownLatch.getCount());
        Thread.sleep(1000);
//        countDownLatch.countDown();
    }

}
